<?php
namespace app\admin\controller;
use app\common\controller\CommonController;
use app\common\errcode\AdminErrCode;
use app\common\errcode\AdminErrMsg;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\Loader;

class LoginController extends CommonController
{
    protected $loginModel;

    public function __construct()
    {
        parent::__construct();
        $this->loginModel = new \app\admin\model\LoginModel();
    }

    /**
     * 后台登录
     * @param string username
     * @param string password
     */
    public function login()
    {
        try {
            if($this->request->isPost()){
                $data = $this->request->post();
                $validate = Loader::validate('User');
                $check = $validate->scene('login')->check($data);
                if(!$check){
                    return $this->jsonJump(AdminErrCode::PARAM_ERROR,AdminErrMsg::PARAM_ERROR.','.$validate->getError());  
                }  
                $res = $this->loginModel->find(trim($data['username']),trim($data['password']));
                if(empty($res)) return $this->jsonJump(AdminErrCode::LOGIN_FAIL,AdminErrMsg::LOGIN_FAIL);
                if($res){
                    $res['jwt'] = $this->create_jwt($res);
                    return $this->jsonJump(AdminErrCode::SUCCESS,AdminErrMsg::SUCCESS,$res);
                }
            }
        } catch (\Exception $e) {
            return $this->jsonJump(AdminErrCode::SYSTEM_ERROR,AdminErrMsg::SYSTEM_ERROR . ',错误信息:'. $e->getMessage());
        }
    }

    /**
     * 登录成功生成jwt
     * @param array info 信息
     */
    protected function create_jwt($info){
        $key = Config('admin_key'); //jwt的签发密钥，验证token的时候需要用到
        $token = array(
            "userinfo" => $info,
            "iss" => "souixu-xinchuang-admin",//签发组织
            "aud" => "souixu-xinchuang-admin",//签发作者
            "iat" => time(),
            "nbf" => time(),
            "exp" => time() + 24*3600
        );
        $jwt = JWT::encode($token, $key, 'HS256');
        return $jwt;
    }
}